<template>
    <div class="page">
        <div class="container">
            <div class="right">
                <img class="logo" src="@/assets/login-logo.png" alt="" />
                <div class="form-box">
                    <div class="title">登录</div>
                    <a-form
                        :model="formState"
                        :label-col="{ style: { width: '35px' } }"
                        labelAlign="left"
                        :rules="rules"
                        @finish="onFinish"
                    >
                        <a-form-item name="phone">
                            <a-input
                                v-model:value="formState.phone"
                                placeholder="请输入账号"
                            />
                        </a-form-item>
                        <a-form-item name="code" class="code">
                            <a-input
                                v-model:value.trim="formState.code"
                                placeholder="请输入验证码"
                                autocomplete="off"
                            >
                                <template #suffix>
                                    <span class="code-btn" @click="hdlGetCode"
                                        >{{ codeTxt }}
                                    </span>
                                </template>
                            </a-input>
                        </a-form-item>
                        <a-form-item>
                            <a-button class="submit" html-type="submit">
                                <span> 登录</span>
                            </a-button>
                        </a-form-item>
                        <div class="tips">
                            点击即表示已阅读并接受使用 <span>用户协议</span> 和
                            <span>隐私协议</span>
                        </div>
                    </a-form>
                </div>
            </div>
        </div>

        <Verify
            mode="pop"
            :captchaType="captchaType"
            :imgSize="{ width: '400px', height: '200px' }"
            ref="verify"
            @success="verifySuccess"
            v-if="isFree"
        ></Verify>
    </div>
</template>

<script setup lang="ts">
    import loginService from "@/service/login.service";
    import {
        computed,
        defineAsyncComponent,
        nextTick,
        onMounted,
        reactive,
        ref,
    } from "vue";
    import { LoginParams } from "@/type/login";
    import { Rule } from "ant-design-vue/es/form";
    import getRuleByName from "@/utils/formRules";
    import { useRouter } from "vue-router";
    import useGlobalStore from "@/stores/global.store";
    import { storeToRefs } from "pinia";
    import { message } from "ant-design-vue";
    // import Verify from "@/components/verifition/Verify.vue";

    const Verify = defineAsyncComponent(
        () => import("@/components/verifition/Verify.vue"),
    );

    const isFree = ref(false);
    onMounted(() => {
        requestIdleCallback((deadline) => {
            if (deadline.timeRemaining() > 0) {
                isFree.value = true;
            }
        });
    });

    const verify = ref();
    const captchaType = ref("");

    const globalStore = useGlobalStore();
    const { setToken, setUserInfo, setExpires_in } = globalStore;
    const { userInfo } = storeToRefs(globalStore);

    const router = useRouter();

    const rules: Record<string, Rule[]> = {
        phone: [getRuleByName("required", "请输入手机号")],
        code: [getRuleByName("required", "请输入验证码")],
    };
    // 超管账号
    const formState = reactive<LoginParams>({
        phone: "",
        code: "",
        captchaVerification: "",
    });

    const pageLoading = ref(false);

    const onFinish = async () => {
        try {
            if (pageLoading.value) {
                return;
            }
            let res = await loginService.login(formState);
            if (res.data.status_code != 0) {
                saveLoginData(res);
            }
        } catch (err) {
            console.log(err);
        }
    };

    const saveLoginData = async (res: any) => {
        let data0 = res.data.result.data || {};
        localStorage.setItem("loginPhone", formState.phone);
        localStorage.setItem("token", data0.access_token);
        localStorage.setItem("expires_in", data0.expires_in.toString());
        setToken(data0.access_token);
        setExpires_in(data0.expires_in);

        let res1 = await loginService.getUserInfo();
        let info = res1.data.result.data;
        setUserInfo({ ...userInfo.value, ...info });
        localStorage.setItem(
            "userInfo",
            JSON.stringify({ ...userInfo.value, ...info }),
        );
        router.replace("/workbench");
    };

    const onShow = (type: "blockPuzzle" | "clickWord") => {
        captchaType.value = type;
        verify.value.show();
    };
    const showVidate = () => {
        onShow("blockPuzzle");
        // if (Math.random() > 0.5) {
        //     onShow("blockPuzzle"); // 滑块
        // } else {
        //     onShow("clickWord"); // 点击文字
        // }
    };

    const verifySuccess = async (cv: any) => {
        try {
            formState.captchaVerification = cv.captchaVerification;
            await loginService.code(formState.phone);
            let time = 60;
            let timer: any;
            if (time != 60) {
                return;
            }

            codeLoading = true;
            const calcTime = () => {
                codeTxt.value = `${time} 秒`;
                timer = setTimeout(() => {
                    time -= 1;
                    if (time > 0) {
                        calcTime();
                    } else {
                        timer && clearTimeout(timer);
                        codeLoading = false;
                        time = 60;
                        codeTxt.value = "重新发送";
                    }
                }, 1000);
            };

            calcTime();
        } catch (err) {
            console.log(err);
        }
    };

    let codeLoading = false;
    const codeTxt = ref("获取验证码");
    const hdlGetCode = async () => {
        if (codeLoading) {
            return;
        }
        if (!formState.phone) {
            return message.warning("请输入手机号");
        }
        showVidate();
    };
</script>

<style lang="scss" scoped src="./Login.scss"></style>
